Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
Using Intersection Observer and EventListeners || Registering keypresses only while specific element is visible

I'm attempting to add an event listener to the document element, which remains active only while a specific section element is within the visible portion of the viewport.

This listener listens for two keypresses, ArrowLeft and ArrowRight, and calls matching functions moveLeft() and moveRight() for each case. Once the section is no longer visible within the viewport the eventListener is to be removed.

const cObserverHandler = entries => {
    const [entry] = entries;

    const keyListener = e => {
        if (e.key === 'ArrowLeft') moveLeft();
        else if (e.key === 'ArrowRight') moveRight();
    };
    if (entry.isIntersecting) {
        console.log('intersect');
        document.addEventListener('keyup', keyListener);
    } else if (!entry.isIntersecting) {
        console.log('depart');
        document.removeEventListener('keyup', keyListener);
    }
};

For brevity I've excluded the IntesectionObserver setup and larger app functioning.

As well, to those not already familiar, within this context entry.isIntersecting will evaluate to a Boolean value based on whether the aforementioned section is within the visible area of the viewport.

El problema:

Examining the console, the messages 'intersect' and 'depart' fire during my scroll testing at the expected times. However, some further stress-testing has shown that arrow presses are being registered and acted on even after the point at which the listener should be removed. Any thoughts on why this might be?

Thanks for reading.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!